package com.ruoyi.develop.factory.factoryProduceMain.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.factory.factoryProduceSale.domain.FactoryProduceSale;
import com.ruoyi.develop.factory.factoryProduceSale.service.IFactoryProduceSaleService;
import com.ruoyi.develop.factory.factoryProduceSaleAll.domain.FactoryProduceSaleAll;
import com.ruoyi.develop.factory.factoryProduceSaleAll.mapper.FactoryProduceSaleAllMapper;
import com.ruoyi.develop.goodsOrderMaterials.domain.GoodsOrderMaterials;
import com.ruoyi.develop.goodsOrderMaterials.service.IGoodsOrderMaterialsService;
import com.ruoyi.develop.goodsSaleMaterial.domain.GoodsSaleMaterial;
import com.ruoyi.develop.goodsSaleMaterial.service.IGoodsSaleMaterialService;
import com.ruoyi.develop.goodsSaledoGongxu.domain.GoodsSaledoGongxu;
import com.ruoyi.develop.goodsSaledoGongxu.service.IGoodsSaledoGongxuService;
import com.ruoyi.develop.lnGongyi.domain.LnGongyi;
import com.ruoyi.develop.lnGongyi.service.ILnGongyiService;
import com.ruoyi.develop.lnGongyigongxu.domain.LnGongyigongxu;
import com.ruoyi.develop.lnGongyigongxu.service.ILnGongyigongxuService;
import com.ruoyi.develop.lnGongyigoods.domain.LnGongyigoods;
import com.ruoyi.develop.lnGongyigoods.service.ILnGongyigoodsService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.develop.factory.factoryProduceMain.domain.FactoryProduceMain;
import com.ruoyi.develop.factory.factoryProduceMain.service.IFactoryProduceMainService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.bean.BeanUtils;

/**
 * 生产订单信息Controller
 * @author qh
 * @date 2024-11-06
 */
@RestController
@RequestMapping("/factoryProduceMain/factoryProduceMain")
public class FactoryProduceMainController extends BaseController {
    @Autowired
    private IFactoryProduceMainService factoryProduceMainService;
    @Autowired
    private FactoryProduceSaleAllMapper factoryProduceSaleAllMapper;
    @Autowired
    private IFactoryProduceSaleService iFactoryProduceSaleService;
    @Autowired
    private IGoodsSaleMaterialService iGoodsSaleMaterialService;
    @Autowired
    private ILnGongyiService iLnGongyiService;
    @Autowired
    private IGoodsSaledoGongxuService iGoodsSaledoGongxuService;
    @Autowired
    private ILnGongyigoodsService lnGongyigoodsService;
    @Autowired
    private ILnGongyigongxuService iLnGongyigongxuService;
    @Autowired
    private IGoodsOrderMaterialsService iGoodsOrderMaterialsService;
    /**
     * 查询生产订单信息列表
     */
    @PreAuthorize("@ss.hasPermi('develop:FactoryProduceMain:query')")
    @GetMapping("/list")
    public TableDataInfo list(FactoryProduceMain entity) {
        startPage();
        List<FactoryProduceMain> list = factoryProduceMainService.selectList(entity);
        return getDataTable(list);
    }

    /**
     * 导出生产订单信息列表
     */
    @PreAuthorize("@ss.hasPermi('develop:FactoryProduceMain:export')")
    @Log(title = "生产订单信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FactoryProduceMain entity) {
        List<FactoryProduceMain> list = factoryProduceMainService.selectList(entity);
        ExcelUtil<FactoryProduceMain> util = new ExcelUtil<FactoryProduceMain>(FactoryProduceMain. class);
        util.exportExcel(response, list, "生产订单信息数据");
    }

    /**
     * 获取生产订单信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('develop:FactoryProduceMain:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(factoryProduceMainService.selectById(id));
    }

    /**
     * 新增生产订单信息
     */
    @PreAuthorize("@ss.hasPermi('develop:FactoryProduceMain:add')")
    @Log(title = "生产订单信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody FactoryProduceMain entity) {
        return toAjax(factoryProduceMainService.insert(entity));
    }

    /**
     * 修改生产订单信息
     */
    @PreAuthorize("@ss.hasPermi('develop:FactoryProduceMain:edit')")
    @Log(title = "生产订单信息", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody FactoryProduceMain entity) {
        return toAjax(factoryProduceMainService.update(entity));
    }

    /**
     * 删除生产订单信息
     */
    @PreAuthorize("@ss.hasPermi('develop:FactoryProduceMain:remove')")
    @Log(title = "生产订单信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(factoryProduceMainService.deleteByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('develop:FactoryProduceMain:remove')")
    @Log(title = "生产订单信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/removeNoGoods/{id}")
    public AjaxResult removeNoGoods(@PathVariable String id) {
        FactoryProduceSaleAll factoryProduceSaleAll=new FactoryProduceSaleAll();
        factoryProduceSaleAll.setProduceId(id);
        List<FactoryProduceSaleAll> factoryProduceSaleAlls=factoryProduceSaleAllMapper.selectList(factoryProduceSaleAll);
        if(factoryProduceSaleAlls.size()>0){
            return AjaxResult.error("请先删除生产订单下的产品，再删除生产单！");
        }
        return toAjax(factoryProduceMainService.deleteById(id));
    }

    @Log(title = "提交生产单", businessType = BusinessType.UPDATE)
    @GetMapping("/submitProduct")
    public AjaxResult submitProduct(FactoryProduceMain factoryProduceMain, HttpServletRequest request) {
        String  goodsSaledoIds =  request.getParameter("goodsSaledoIds");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String today = sdf.format(new Date());
        String codeMaxString = factoryProduceMainService.selectMaxCode(today);
        if(StringUtils.isNotBlank(codeMaxString)){
            // 最大编号+1
            codeMaxString = Long.parseLong(codeMaxString)+1+"";
        }else{
            codeMaxString = today+"0001";
        }
        FactoryProduceMain entity =new FactoryProduceMain();
        entity.setStatus(BusinessConstants.PROD_STATUS_1);
        entity.setIpoNo(codeMaxString);
        entity.setIpoType("1");
        entity.setType(factoryProduceMain.getType());
        entity.setIpoStatus(BusinessConstants.FACTORP_PROD_STATUS_1);
        entity.setPlantName("鲁能光大");
        entity.setSaleDate(factoryProduceMain.getSaleDate());
        entity.setPlanStartDate(factoryProduceMain.getPlanStartDate());
        entity.setPlanFinishDate(factoryProduceMain.getPlanFinishDate());
        entity.setWorkshopName(factoryProduceMain.getWorkshopName());
        entity.setType(factoryProduceMain.getType());
        //entity.setWorkshopName("1-7车间");
        //entity.setPlanStartDate(new Date());
        //entity.setPlanFinishDate(new Date());
        factoryProduceMainService.insertMain(entity);
        for (String  goodsSaledoId : goodsSaledoIds.split(",")) {
            FactoryProduceSaleAll factoryProduceSaleAll = factoryProduceSaleAllMapper.selectById(goodsSaledoId);
            factoryProduceSaleAll.setProduceId(entity.getId());
            factoryProduceSaleAll.setProduceNo(entity.getIpoNo());
            factoryProduceSaleAll.setStatus(BusinessConstants.PROD_STATUS_1);
            factoryProduceSaleAll.setType(factoryProduceMain.getType());
            //factoryProduceSaleAll.setIssheding(BusinessConstants.PROD_STATUS_2);//已分配工艺工序
            factoryProduceSaleAllMapper.update(factoryProduceSaleAll);
            List<FactoryProduceSale> factoryProduceSaleList=iFactoryProduceSaleService.selectByParentId(factoryProduceSaleAll.getId());
            if(factoryProduceSaleList.size()>0){
                for(FactoryProduceSale factoryProduceSale:factoryProduceSaleList){
                    factoryProduceSale.setProduceId(entity.getId());
                    factoryProduceSale.setProduceNo(entity.getIpoNo());
                    factoryProduceSale.setStatus(BusinessConstants.PROD_STATUS_1);
                    iFactoryProduceSaleService.update(factoryProduceSale);
                }
            }
            iGoodsSaleMaterialService.deleteBySaleId(entity.getId());
            // TODO 如果是质检提交来的 请购单 没有goodsSale
            //合并请购产品的工艺设定
            if(StringUtils.isNotBlank(factoryProduceSaleAll.getGoodsId())) {
                LnGongyi lnGongyi=iLnGongyiService.selectById(factoryProduceSaleAll.getGoodsId());
                if(lnGongyi!=null) {
                    factoryProduceSaleAll.setGongyiId(lnGongyi.getId());
                    factoryProduceSaleAll.setGongyiName(lnGongyi.getName());
                    factoryProduceSaleAll.setGongyiCode(lnGongyi.getCode());
                    factoryProduceSaleAll.setGongyiFile(lnGongyi.getFile());
                    factoryProduceSaleAll.setGongyiPhoto(lnGongyi.getPhoto());
                    factoryProduceSaleAll.setGongyiShuoming(lnGongyi.getShuoming());
                    factoryProduceSaleAll.setStatus(BusinessConstants.PROD_STATUS_2);//已分配工艺工序
                    factoryProduceSaleAll.setIssheding(BusinessConstants.PROD_STATUS_2);//已分配工艺工序
                    factoryProduceSaleAllMapper.update(factoryProduceSaleAll);
                }
            }
            //合并请购产品的工序设定
            iGoodsSaledoGongxuService.deleteBySaleId(factoryProduceSaleAll.getId());
            List<LnGongyigoods> lnGongyigongxuList=lnGongyigoodsService.selectByGoods(factoryProduceSaleAll.getGoodsId());
            if(lnGongyigongxuList.size()>=1){
                List<LnGongyigongxu> lnGongyigongxus=iLnGongyigongxuService.selectByGongyi(lnGongyigongxuList.get(0).getGongyiId());
                if(lnGongyigongxus!=null){
                    factoryProduceSaleAll.setStatus(BusinessConstants.PROD_STATUS_2);//已分配工艺工序
                    factoryProduceSaleAll.setIssheding(BusinessConstants.PROD_STATUS_2);//已分配工艺工序
                    factoryProduceSaleAllMapper.update(factoryProduceSaleAll);
                    for (LnGongyigongxu entity1 : lnGongyigongxus) {
                        GoodsSaledoGongxu goodsSaledoGongxu = new GoodsSaledoGongxu();
                        goodsSaledoGongxu.setSaleId(factoryProduceSaleAll.getId());
                        goodsSaledoGongxu.setGoodsId(factoryProduceSaleAll.getGoodsId());
                        goodsSaledoGongxu.setGongyiId(factoryProduceSaleAll.getGongyiId());
                        goodsSaledoGongxu.setGongyiName(factoryProduceSaleAll.getGongyiName());
                        goodsSaledoGongxu.setGongyiCode(factoryProduceSaleAll.getGongyiCode());
                        goodsSaledoGongxu.setGongxuId(entity1.getId());
                        goodsSaledoGongxu.setCode(entity1.getCode());
                        goodsSaledoGongxu.setName(entity1.getName());
                        goodsSaledoGongxu.setPhoto(entity1.getPhoto());
                        goodsSaledoGongxu.setFile(entity1.getFile());
                        goodsSaledoGongxu.setShuoming(entity1.getShuoming());
                        goodsSaledoGongxu.setMoney(entity1.getMoney());
                        goodsSaledoGongxu.setGongxuName(entity1.getGoodsName());
                        goodsSaledoGongxu.setGongxuModel(entity1.getGoodsModel());
                        goodsSaledoGongxu.setDeptId(entity1.getDeptId());
                        goodsSaledoGongxu.setDeptName(entity1.getDeptName());
                        goodsSaledoGongxu.setWorkHour(entity1.getWorkHour());
                        goodsSaledoGongxu.setCounts(factoryProduceSaleAll.getCount());
                        goodsSaledoGongxu.setFenpeiCount(BigDecimal.ZERO);
                        goodsSaledoGongxu.setRemainCount(factoryProduceSaleAll.getCount());
                        goodsSaledoGongxu.setFinishCount(BigDecimal.ZERO);
                        goodsSaledoGongxu.setRemainfinishCount(factoryProduceSaleAll.getCount());
                        goodsSaledoGongxu.setXuhao(entity1.getIdx());;
                        goodsSaledoGongxu.setIslast(entity1.getIslast());
                        iGoodsSaledoGongxuService.insert(goodsSaledoGongxu);
                    }
                }
            }

            List<GoodsOrderMaterials> goodsOrderMaterialsList = iGoodsOrderMaterialsService.selectByGoodsId(factoryProduceSaleAll.getGoodsId());
            if(goodsOrderMaterialsList.size() > 0){
                factoryProduceSaleAll.setIschaijie(BusinessConstants.TYPE_CHAIJIE_YES);//已拆解
                factoryProduceSaleAllMapper.update(factoryProduceSaleAll);
                for(GoodsOrderMaterials goodsOrderMaterials:goodsOrderMaterialsList){
                    GoodsSaleMaterial goodsSaleMaterial=new GoodsSaleMaterial();
                    BeanUtils.copyProperties(goodsOrderMaterials, goodsSaleMaterial, "id");
                    goodsSaleMaterial.setGsaleId(factoryProduceSaleAll.getId());
                    goodsSaleMaterial.setGoodsId(goodsOrderMaterials.getMaterialId());
                    /*goodsSaleMaterial.setSupplierId(factoryProduceSaleAll.getSupplierId());
                    goodsSaleMaterial.setSupplierName(factoryProduceSaleAll.getSupplierName());*/
                    goodsSaleMaterial.setProjectId(factoryProduceSaleAll.getProjectId());
                    goodsSaleMaterial.setProjectNo(factoryProduceSaleAll.getProjectNo());
                    if(factoryProduceSaleAll.getCount() !=null && factoryProduceSaleAll.getCount().compareTo(BigDecimal.ZERO)>0 &&
                            goodsOrderMaterials.getGoodsCount() !=null && goodsOrderMaterials.getGoodsCount().compareTo(BigDecimal.ZERO)>0  ) {
                            goodsSaleMaterial.setGoodsCount(factoryProduceSaleAll.getCount().multiply(goodsOrderMaterials.getGoodsCount()));
                            goodsSaleMaterial.setShengyuCount(factoryProduceSaleAll.getCount().multiply(goodsOrderMaterials.getGoodsCount()));
                        /*if(goodsSaledo.getGoodsBuyPrice() !=null && goodsSaledo.getGoodsBuyPrice().compareTo(BigDecimal.ZERO)>0){
                            goodsSaleMaterial.setGoodsBuyTotal(goodsSaledo.getPleaseBuyCount().multiply(goodsOrderMaterials.getGoodsCount()).multiply(goodsOrderMaterials.getGoodsBuyPrice()));
                        }*/
                    }
                    iGoodsSaleMaterialService.insert(goodsSaleMaterial);
                }
            }
        }
        return AjaxResult.success("订单生成完成！");
    }
}
